import React from 'react';
import {
  Button,
  Popconfirm,
  Space,
  Modal,
  Form,
  Input,
  Select,
  Row,
  Col,
  DatePicker,
  message,
} from 'antd';
import { PlusOutlined, DeleteOutlined, FormOutlined, RedoOutlined } from '@ant-design/icons';
import Cookie from 'js-cookie';
import TableCom from '../../../Component/tableCompoment/index';
import { listUser, getRouters } from '../../../service/auth';
const { Option } = Select;
let time;
class personManage extends React.Component {
  formRef = React.createRef();
  constructor(prop) {
    super(prop);
    this.state = {
      params: {
        pageNo: 1,
        pageSize: 10,
      },
      btnStyle: 'button-color-daybreak',
      column: [
        {
          title: '用户编号',
          dataIndex: 'userId',
          key: 'userId',
        },
        {
          title: '用户名称',
          dataIndex: 'userName',
          key: 'userName',
        },
        {
          title: '手机号码',
          dataIndex: 'phoneNumber',
          key: 'phoneNumber',
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime',
        },
        {
          title: '部门',
          dataIndex: 'dept[deptName]',
          key: 'department',
        },
        {
          title: '用户类型',
          dataIndex: 'userType',
          key: 'userType',
        },
        {
          title: '操作',
          dataIndex: 'operation',
          render: (_, record) =>
            this.state.tableData.length >= 1 ? (
              <Space>
                <Popconfirm
                  cancelText="取消"
                  okText="确定"
                  title="确定删除此条数据吗?"
                  onConfirm={() => this.handleDelete(record.userId)}
                >
                  <Button
                    icon={<DeleteOutlined />}
                    className={this.state.btnStyle + ' ' + 'button-noback'}
                  >
                    删除
                  </Button>
                </Popconfirm>
                <Button
                  onClick={this.handleEdit.bind(this, record)}
                  icon={<FormOutlined />}
                  className={this.state.btnStyle + ' ' + 'button-noback'}
                >
                  修改
                </Button>
                <Button
                  onClick={this.handleReset.bind(this, record)}
                  icon={<RedoOutlined />}
                  className={this.state.btnStyle + ' ' + 'button-noback'}
                >
                  重置密码
                </Button>
              </Space>
            ) : null,
        },
      ],
      tableData: [], //表格数据
      top: 'none', //顶部是否有分页器及分页器位置
      bottom: 'bottomCenter', //底部是否有分页器及分页器位置
      visible: false, //modal框是否显示
      confirmLoading: false, //确定延时，异步回调
      Title: '', //modal标题
      layout: {
        //表单位置
        labelCol: { span: 4 },
        wrapperCol: { span: 16 },
      },
      modalLayout: {
        //模态框表单位置
        labelCol: { span: 8 },
        wrapperCol: { span: 16 },
      },
      initValue: {},
      isResetPwd: false,
    };
  }
  //删除人员
  handleDelete = val => {
    let tableData = [...this.state.tableData];
    tableData.map((item, index) => {
      if (item.userId === val) {
        tableData.splice(index, 1);
      }
      return item;
    });
    this.setState({
      tableData,
    });
  };
  //修改数据
  handleEdit = (val, e) => {
    let initValue = val;
    console.log(val);
    this.setState({
      Title: `修改${val.userName}信息`,
      visible: true,
      initValue,
      isResetPwd: false,
    });
  };
  //modal框确定
  handleOk = () => {
    this.formRef.current
      .validateFields()
      .then(values => {
        this.formRef.current.resetFields();
        console.log(values);
        let obj = {
          key: '4',
          userId: '4',
          userName: values.userName,
          tellPhone: values.tellPhone,
          insertTime:
            new Date().getFullYear() + '-' + new Date().getMonth() + 1 + '-' + new Date().getDate(),
          department: values.department,
          userType: values.userType,
          password: values.password,
        };
        let tableData = [...this.state.tableData];
        tableData.push(obj);
        this.setState({
          visible: false,
          tableData,
        });
      })
      .catch(info => {
        message.error('请正确填写数据!');
      });
  };
  //modal取消
  handleCancel = () => {
    this.setState({
      visible: false,
      isResetPwd: false,
    });
  };
  //新增
  handleAdd = () => {
    this.setState({
      Title: `新增用户`,
      visible: true,
    });
  };
  //重置密码
  handleReset = (val, e) => {
    this.setState({
      Title: `重置${val.userName}的密码`,
      visible: true,
      isResetPwd: true,
    });
  };
  //搜索
  onFinish = val => {
    console.log(val);
    //val代表表单输入的值，在这里进行搜索
  };
  //重置
  onReset = () => {
    this.formRef.current.resetFields();
  };
  //下拉列表框值改变
  onGenderChange = value => {
    // console.log(value);
  };
  renderModal = () => {
    let { modalLayout, initValue, isResetPwd } = this.state;
    if (!isResetPwd) {
      return (
        <>
          <Form {...modalLayout} ref={this.formRef} initialValues={initValue}>
            <Row gutter={24}>
              <Col span="12">
                <Form.Item
                  name="userName"
                  label="用户名称"
                  rules={[
                    {
                      required: true,
                      message: '用户名称',
                    },
                  ]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span="12">
                <Form.Item
                  name="tellPhone"
                  label="手机号码"
                  validateTrigger="onBlur"
                  rules={[
                    {
                      required: true,
                      validator: (_, value) =>
                        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(
                          value
                        )
                          ? Promise.resolve()
                          : Promise.reject(new Error('请输入正确的电话号码')),
                    },
                  ]}
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col span="12">
                <Form.Item
                  name="department"
                  label="部门"
                  rules={[
                    {
                      required: true,
                      message: '部门不能为空',
                    },
                  ]}
                >
                  <Select placeholder="请选择部门" onChange={this.onGenderChange} allowClear>
                    <Option value="董事长">董事长</Option>
                    <Option value="财务部">财务部</Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span="12">
                <Form.Item
                  name="userType"
                  label="用户类型"
                  rules={[
                    {
                      required: true,
                      message: '用户类型不能为空',
                    },
                  ]}
                >
                  <Select placeholder="请选择用户类型" onChange={this.onGenderChange} allowClear>
                    <Option value="超级管理员">超级管理员</Option>
                    <Option value="部门经理">部门经理</Option>
                    <Option value="普通员工">普通员工</Option>
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col span="12">
                <Form.Item
                  name="password"
                  label="密码"
                  rules={[
                    {
                      required: true,
                      message: '请输入密码',
                    },
                  ]}
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </>
      );
    } else {
      return (
        <>
          <Form {...modalLayout} ref={this.formRef}>
            <Row gutter={24}>
              <Col span="20">
                <Form.Item
                  name="pwd"
                  label="新密码"
                  rules={[
                    {
                      required: true,
                      message: '请输入您的新密码',
                    },
                  ]}
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </>
      );
    }
  };
  //给表格的数据加key字段
  changeData = () => {
    if (!this.state.tableData[0]?.key) {
      let tableData = this.state.tableData;
      tableData.forEach(item => {
        item.key = item.userId;
      });
    }
  };
  render() {
    if (this.state.tableData.length > 0) this.changeData();
    const { Title, visible, confirmLoading, column, tableData, top, bottom, layout } = this.state;
    return (
      <>
        <div className="topSelect">
          <Form {...layout} ref={this.formRef} onFinish={this.onFinish}>
            <Row gutter={24}>
              <Col span="6">
                <Form.Item name="userName" label="用户名称">
                  <Input />
                </Form.Item>
              </Col>
              <Col span="6">
                <Form.Item name="tellPhone" label="手机号码">
                  <Input />
                </Form.Item>
              </Col>
              <Col span="6">
                <Form.Item name="department" label="部门">
                  <Select
                    placeholder="请选择要查询的部门"
                    onChange={this.onGenderChange}
                    allowClear
                  >
                    <Option value="male">male</Option>
                    <Option value="female">female</Option>
                    <Option value="other">other</Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span="6">
                <Form.Item>
                  <Button type="primary" htmlType="submit">
                    搜索
                  </Button>
                  <Button htmlType="button" onClick={this.onReset}>
                    重置
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </div>
        <div className="topOperation">
          <Button type="primary" onClick={this.handleAdd} icon={<PlusOutlined />}>
            新增
          </Button>
        </div>
        <div className="tableCont">
          <TableCom
            tableColumns={column}
            tableData={tableData}
            top={top}
            bottom={bottom}
            isSelect={true}
          ></TableCom>
        </div>
        <Modal
          okText={'确定'}
          cancelText={'取消'}
          title={Title}
          visible={visible}
          onOk={this.handleOk}
          confirmLoading={confirmLoading}
          onCancel={this.handleCancel}
        >
          {this.renderModal()}
        </Modal>
      </>
    );
  }
  componentDidMount() {
    //表格按钮颜色
    let that = this;
    let tableData;
    time = setInterval(function () {
      if (Cookie.get('btnColor')) {
        if (that.state.btnStyle !== Cookie.get('btnColor')) {
          that.setState({
            btnStyle: Cookie.get('btnColor'),
          });
        }
      }
    }, 500);
    // 获取表格数据;
    listUser('/user/list', this.state.params).then(res => {
      console.log(res.data.list);
      if (res.code === 200) tableData = res.data.list;
      this.setState({
        btnStyle: Cookie.get('btnColor') || 'button-color-daybreak',
        tableData,
      });
    });
  }
  componentWillUnmount() {
    clearInterval(time);
  }
}
export default personManage;
